<script setup>
import {ref, computed, watch, onActivated} from "vue";
import {useStore} from "vuex";
import {ElMessage, ElMessageBox} from "element-plus";
import {onMounted} from "vue";
import axios from "axios";

let store = useStore();
const input1 = ref('')
const input2 = ref('')
const numArr = ref([])

// 通知标题
let title = ref('');
// 通知内容
let content = ref('');

// 定义 完结状态 选项
const finishStatusOptions = [
  { label: '接受预约（未完成）', value: 0 },
  { label: '不接受预约', value: 1 },
  { label: '咨询完成', value: 2 },
  { label: '取消预约', value: 3 },
];
const dialogFormVisible = ref(false);

const handleSelectionChange = (selection) => {
  numArr.value = selection.map(item => item.consultantId);
};

const form = ref({
  realname: '',
  consultationappointmentList:{
    consultant:{
      consultantId:null,
    },
    content:'',
    startTime:'',
    endTime:'',
    finishStatus:'',
    consultantId:null,
    appointmentId:null,
  },
});

// 封装一个方法来处理分页数据
const processPaginatedData = () => {
  // 计算当前页的起始索引和结束索引
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;

  // 获取当前页的数据
  const currentPageData = store.state.AppointmentForm.slice(start, end);

  // 遍历当前页的数据
  currentPageData.forEach((item, index) => {
    // 这里可以对每个 item 进行处理
    // 例如打印每个 item 的 consultationappointmentList
    // console.log(`Item ${index + 1} in page ${currentPage.value}:`, item.consultationappointmentList);
  });
};

//前端分页
const currentPage = ref(1);
const pageSize = ref(5); // 每页显示的条目数
const total = computed(() => store.state.AppointmentForm.length); // 总条目数
const ConsultantOnCurrentPage = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  // console.log(store.state.AppointmentForm.slice(start, end)[0].consultationappointmentList)
  processPaginatedData();
  return store.state.AppointmentForm.slice(start, end);
});
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};



onMounted(async () => {
  await fetchConsultant();
});

//修改完结状态
const updateFinishStatus = async (row) => {
  try {
    const appointmentId = row.consultationappointmentList[0].appointmentId; // 假设每个预约都有一个唯一的 ID
    const newFinishStatus = row.consultationappointmentList[0].finishStatus;

    // 发送 PUT 请求更新完结状态
    const response = await axios.put(`/consultationappointment`, null,{
      params: {
        appointmentId: appointmentId,
        finishStatus: newFinishStatus,
      },
    });
    console.log(response.data);

    if (response.data.code === 200) {
      if (newFinishStatus == 0){
          title.value = "预约成功";
          content.value = "您已预约成功，请在规定的时间内咨询心理咨询师。"
      }else if (newFinishStatus == 1){
          title.value = "预约失败";
          content.value = "对不起，该咨询师暂时没有空闲时间。"
      }else if (newFinishStatus == 2){
          title.value = "咨询完成";
          content.value = "感谢您的咨询，希望您能早日康复。"
      }else if (newFinishStatus == 3){
          title.value = "取消预约";
          content.value = "您已取消预约，请重新预约。"
      }
      axios.post("/insertNotification",{
        memberId:row.consultationappointmentList[0].memberId,
        title:title.value,
        content:content.value
      },{
        headers:{"Content-Type":"multipart/form-data"}
      })
        .then(resp => {
          console.log(resp.data)
        })
          .catch(err => {
          console.error(err)
        })
      ElMessage({
        type: 'success',
        message: '状态更新成功',
      });
    } else {
      ElMessage({
        type: 'error',
        message: response.data.message || '状态更新失败，请稍后再试',
      });
    }
  } catch (error) {
    console.error('更新完结状态时发生错误:', error);
    ElMessage({
      type: 'error',
      message: '状态更新过程中发生错误',
    });
  }
};

// 重新获取所有用户信息的方法
const fetchConsultant = async () => {
  try {
    const resp = await axios.get("/member/consultation");
    console.log(resp.data.data);
    const appointment = resp.data.data;
    store.commit("setAppointmentForm", appointment);
    store.commit("setOriginalConsultantForm", appointment);


  } catch (err) {
    console.error(err);
  }
};

//显示全部
const resetConsultant = () => {
  fetchConsultant();
  currentPage.value = 1; // 重置分页回到第一页
};

//删除咨询师
const deleteConsultant = async (consultant) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
        `确定要删除该记录吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    // 发送 DELETE 请求给后端删除员工信息 批量删除
    const response = await axios.delete(`/consultant/deleteConsultant/${consultant.consultantId}`)

    if (response.data.code === 200) { // 假设 R.ok() 返回的状态码是 200
      // 成功后更新 Vuex store 中的用户列表
      store.commit('deleteConsultant', consultant.consultantId);

      // 给出成功的消息提示
      ElMessage({
        type: 'success',
        message: '删除成功'
      });

      //   重新获取咨询师列表
      await fetchConsultant();

    } else {
      // 如果有错误信息，显示错误消息
      ElMessage({
        type: 'error',
        message: response.data.message || '删除失败，请稍后再试'
      });
    }
  } catch (error) {
    console.error('删除咨询师时发生错误:', error);
  }
};

//批量删除咨询师
const deleteConsultantBatch = async () => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
        `确定要删除选中的咨询师吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    // 发送 DELETE 请求给后端删除员工信息 批量删除
    await axios.delete("/consultant/deleteConsultantList", {
      data:numArr.value
    })
        .then(resp => {
          const data = resp.data.data;
          store.commit("setConsultantForm", data);
          console.log(data)
          fetchConsultant()
        })
  }
  catch (error) {
    // 如果用户取消了确认对话框，则 error.message 将包含 "cancel"
    if (error.message !== 'cancel') {
      console.error('删除咨询师时发生错误:', error);
      ElMessage({
        type: 'error',
        message: '已取消删除'
      });
    }
  }
}

//模糊搜索
const searchConsultant = async () => {
  const id = input1.value;
  const name = input2.value;

  try {
    // 发送 GET 请求给后端模糊搜索咨询师信息
    axios.get(`/member/findConsultation?name=${name}`)
        .then(resp => {
          const data = resp.data.data;
          store.commit("setAppointmentForm", data);
          console.log(data)

          // if (data.length === 0){
          //   ElMessage({
          //     type: 'warning',
          //     message: '没有符合条件的咨询师'
          //   });
          // }

          // 重置分页到第一页
          currentPage.value = 1;

          // 更新页面上的咨询师列表
          ConsultantOnCurrentPage.value = computed(() => {
            const start = (currentPage.value - 1) * pageSize.value;
            const end = start + pageSize.value;
            return store.state.AppointmentForm.slice(start, end);
          });

        })
  }
  catch (error) {
    console.error('模糊搜索咨询师时发生错误:', error);
    ElMessage({
      type: 'error',
      message: '模糊搜索过程中发生了错误'
    });
  }

};
</script>

<template>
  <div>
    <div class="right-little-body">
      <div class="little-title">
        <div class="title-top">
          <div class="title-top-left">
            <span>会员姓名：</span>
            <div style="display: inline-block">
              <el-input
                  v-model="input2"
                  style="width: 200px"
                  size="large"
                  placeholder=""
              />
            </div>
          </div>
          <div class="title-top-right">
            <el-button type="primary" @click="searchConsultant">搜索</el-button>
            <el-button type="success" @click="resetConsultant">显示全部</el-button>
          </div>
        </div>
        <div class="title-middle">
          <el-button type="danger" @click="deleteConsultantBatch">批量删除</el-button>
        </div>
        <div class="title-bottom">
          <el-table :data="ConsultantOnCurrentPage"
                    stripe style="width: 1200px"
                    :border="true"
                    @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="咨询师编号" width="120">
              <template #default="scope">
                {{ scope.row.consultationappointmentList[0].consultantId}}
              </template>
            </el-table-column>
            <el-table-column prop="realname" width="120" label="会员姓名"/>
            <el-table-column label="咨询开始时间" width="200">
              <template #default="scope">
                {{ scope.row.consultationappointmentList[0].startTime}}
              </template>
            </el-table-column>
            <el-table-column label="咨询结束时间" width="200">
              <template #default="scope">
                {{ scope.row.consultationappointmentList[0].endTime}}
              </template>
            </el-table-column>
            <el-table-column label="咨询内容" width="240">
              <template #default="scope">
                {{ scope.row.consultationappointmentList[0].content}}
              </template>
            </el-table-column>
            <el-table-column label="完结状态" width="470">
              <template #default="scope">
                <el-radio-group v-model="scope.row.consultationappointmentList[0].finishStatus" @change="updateFinishStatus(scope.row)">
                  <el-radio-button v-for="option in finishStatusOptions" :key="option.value" :label="option.value">
                    {{ option.label }}
                  </el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>

            <el-table-column label="删除">
              <template #default="scope">
                <el-button type="danger" @click="deleteConsultant(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
                layout="prev, pager, next"
                :total="total"
                :page-size="pageSize"
                :current-page="currentPage"
                @current-change="handleCurrentChange"
            />
          </div>


        </div>
      </div>



    </div>
  </div>
</template>

<style scoped>
.right-little-body {
  padding: 20px;
  width: 100%;
  position: relative;
  height: 100%;
}

.little-title {
  width: 100%;
  height: 100%;
  display: inline-block;
}

.title-top {
  width: 100%;
  height: 40px;
}

.title-top-left {
  display: inline-block;
}


.title-top-right {
  display: inline-block;
}

.title-middle {
  margin: 10px 15px;
}

.title-bottom {
  margin: 15px 15px;
}
.pagination {
  margin-top: 20px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader  {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
#el-upload{
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader #el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>